﻿// ------------------------------------------------------------------
// DO NOT REMOVE THIS LINES IN ANY TIMES WILL BE.
// Original author: agehack
// Project name: Putingun
// ------------------------------------------------------------------


using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Drawing;
using System.Windows.Forms;
using Putingun.PVDEngine;
using WMPLib;

namespace Putingun
{
    public partial class wndMain : Window
    {
        public wndMain()
        {
            InitializeComponent();
            App.OnLoadDone(this);

            SetupDesign();
            SetupDosTimer();

            Title = "ПутинВзрываетДома " + App.VersionMark;
            lblSystemInfo.Content = Agehack.SystemVersion.Detect();    // DEBUG FIXME
        }

        #region GUI, GFX
        public void SetupDesign()
        {
            System.Windows.Forms.Timer t = new Timer();
            t.Interval = 40;
            t.Enabled = true;
            t.Start();
            t.Tick += new EventHandler(t_Tick);
        }
        bool back = false;
        void t_Tick(object sender, EventArgs e)
        {
            if (back && lblMsg2.Opacity <= 0.3f)
                back = false;
            else if (!back && lblMsg2.Opacity >= 0.8f)
                back = true;

            if (back)
                    lblMsg2.Opacity -= 0.025f;
            else
            {
                if (Flooder.IsActive)
                    lblMsg2.Opacity += 0.25f;
            }
        }
        #endregion
        #region Онлайн-радио через Windows Media Player (WMPLib)
        public void btnRadioToggle_Click(object sender, RoutedEventArgs e)
        {
            bool wasnull = PvdRadio.Player == null;
            if (PvdRadio.IsPlaying)
                PvdRadio.PlayStop();
            else
            {
                btnRadioToggle.Content = "Подключаем ...";
                PvdRadio.PlayStart(true); // FIXME must be a setting
                PvdRadio.Volume = (int)sdrRadioVolume.Value;
                if (wasnull)
                {
                    PvdRadio.Player.PlayStateChange +=
                        new WMPLib._WMPOCXEvents_PlayStateChangeEventHandler(Player_PlayStateChange);
                    PvdRadio.Player.MediaError +=
                        new WMPLib._WMPOCXEvents_MediaErrorEventHandler(Player_MediaError);
                }
            }
        }
        private void Player_PlayStateChange(int NewState)
        {
            WMPLib.WMPPlayState NState = (WMPLib.WMPPlayState)NewState;
            if (NState == WMPLib.WMPPlayState.wmppsPlaying)
                btnRadioToggle.Content = "Выключть радио";
            else if (NState == WMPPlayState.wmppsBuffering)
                btnRadioToggle.Content = "Буфферизуем ...";
            else
            {
                if (!PvdRadio.IsStopped)
                    PvdRadio.PlayStop();
                PvdRadio.Player = null;
                btnRadioToggle.Content = "Включить радио";
            }
        }
        private void Player_MediaError(object pMediaObject)
        {
            btnRadioToggle.Content = "Ошибка данных";
        }
        private void sdrRadioVolume_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            if (PvdRadio.IsPlaying)
                PvdRadio.Volume = (int)sdrRadioVolume.Value;
        }
        #endregion
        #region Основное
        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            if (!Flooder.IsActive && PvdRadio.IsStopped && !App.UserIsAuthorized)
                App.Exit();

            e.Cancel = true;
            App.ToggleMainWindow();
        }
        private void lblMsg2_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            try
            {
                if (!Flooder.IsActive)
                {
                    if (!rdbDosHTTP.IsChecked.Value)
                        throw new NotImplementedException("TCP/UDP is not implemented yet.");

                    string ip = txtDosAddress.Text;
                    ushort port = 80;
                    if (ip.Contains(":"))
                    {
                        port = Convert.ToUInt16(ip.LastIndexOf(':') + 1);
                        port = Convert.ToUInt16(ip.Substring(port, ip.Length - port));
                        ip = ip.Substring(0, ip.LastIndexOf(":"));
                    }
                    Flooder = new PvdAttack(int.Parse(txtDosThreads.Text), ip, port);
                    Flooder.Response = chkDosResponse.IsChecked.Value;
                    Flooder.Delay = int.Parse(txtDosDelay.Text);
                    Flooder.Timeout = int.Parse(txtDosTimeout.Text) * 1000;
                    Flooder.HttpSubsite = txtDosSubsite.Text;
                    Flooder.HttpHeaders = chkDosHeaders.IsChecked.Value;
                    Flooder.HttpHost = txtDosHost.Text;
                    Flooder.HttpUserAgent = "Opera/9.80 (Windows NT 6.1; U; en) Presto/2.10.229 Version/11.60";
                    Flooder.HttpConnectionKeepAlive = true;
                    Flooder.Start();
                }
                else
                    Flooder.Stop();
            }
            catch (Exception ex)
            {
                System.Windows.MessageBox.Show(
                    ex.Message,
                    "Whatta fuck?!", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
        public PvdAttack Flooder = new PvdAttack(0, "127.0.0.1", 0);
        public void SetupDosTimer()
        {
            System.Windows.Forms.Timer tt = new Timer();
            tt.Interval = 100;
            tt.Enabled = true;
            tt.Start();
            tt.Tick += new EventHandler(tt_Tick);
        }
        void tt_Tick(object sender, EventArgs e)
        {
            if (Flooder.IsActive)
            {
                if (Flooder.IsSleeping)
                    lblStatsState.Content = "Sleeping";
                else lblStatsState.Content = "Flooding";
            }
            else lblStatsState.Content = "Stopped";

            if (!Flooder.IsActive)
                return;

            int[] stats = Flooder.Update();
            lblStatsRequested.Content = stats[0].ToString();
            lblStatsDownloaded.Content = stats[1].ToString();
            lblStatsFailed.Content = stats[2].ToString();
            lblStatsBad.Content = stats[3].ToString();
            int busy = stats[4] + stats[5] + stats[6];
            lblStatsBusy.Content = busy.ToString();
            lblStatsIdle.Content = stats[7].ToString();
        }
        #endregion
    }
}